package org.tc.feign.shopmall.controller;

import Dto.OrdersDto;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.tc.feign.api.AlipayConfig;
import org.tc.feign.api.InfoHolder;
import org.tc.feign.api.ThreadLocalCache;
import org.tc.feign.service.FeignShoppingService;
import org.tc.feign.service.OrdersService2;
import org.tc.shopmall.entity.Orders;
import org.tc.shopmall.entity.PageHelper;
import org.tc.shopmall.entity.ShoppingTest;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import static org.tc.feign.shopmall.controller.DateTest.getYearFirst;
import static org.tc.feign.shopmall.controller.DateTest.getYearLast;


@RestController
@CrossOrigin(origins = {"*"}, methods = {RequestMethod.GET, RequestMethod.POST}, allowCredentials = "true")
public class OrdersController {
    @Autowired
    private OrdersService2 ordersService2;
    @Autowired
    private FeignShoppingService feignShoppingService;

    @RequestMapping("/selectOrdersById")
    public Orders selectOrdersById(@RequestParam Integer id) {
        return ordersService2.selectByPrimaryKey(id);
    }

    @RequestMapping("/insertOrders")
    public int insertOrders(@RequestBody Orders orders) {
        return ordersService2.insert(orders);
    }

    @RequestMapping("/deleteOrdersById")
    public int deleteOrdersById(@RequestParam Integer id) {
        return ordersService2.deleteByPrimaryKey(id);
    }

    @RequestMapping("/selectCountByshy")
    public int selectCountByshy(@RequestParam Integer salesclerkid) {
        System.out.println("查数量");
        return ordersService2.selectCount();
    }

    @RequestMapping("/updateOrder")
    public int updateOrder(@RequestBody Orders orders){
        System.out.println(orders.getMembernumber()+"controller层-------------");
        return ordersService2.updateOrder(orders);
    }

    @RequestMapping("/selectAllOrders")
    public PageHelper<Orders> selectAllOrders(@RequestBody PageHelper pageHelper) {
        System.out.println(pageHelper.getFirstResult() + "\t" + pageHelper.getPageSize());
        List<Orders> list = this.ordersService2.selectAllOrder(pageHelper);
        pageHelper.setData(list);
        int sumCount = ordersService2.selectCount();
        System.out.println(sumCount);
        pageHelper.setPageCount(sumCount);
        System.out.println("分页");
        return pageHelper;
    }

    /**
     * 默认日期格式
     */
    public static String DEFAULT_FORMAT = "yyyy-MM-dd";

    /**
     * 格式化日期
     *
     * @param date 日期对象
     * @return String 日期字符串
     */
    public static String formatDate(Date date) {
        SimpleDateFormat f = new SimpleDateFormat(DEFAULT_FORMAT);
        String sDate = f.format(date);
        return sDate;
    }

    /**
     * 获取当年的第一天
     *
     * @param
     * @return
     */
    public static Date getCurrYearFirst() {
        Calendar currCal = Calendar.getInstance();
        int currentYear = currCal.get(Calendar.YEAR);
        return getYearFirst(currentYear);
    }

    /**
     * 获取当年的最后一天
     *
     * @param
     * @return
     */
    public static Date getCurrYearLast() {
        Calendar currCal = Calendar.getInstance();
        int currentYear = currCal.get(Calendar.YEAR);
        return getYearLast(currentYear);
    }


    /**
     * 获取某个分店本月账单总额
     * 从本月1号到现在的账单总额
     *
     * @return
     */
    @RequestMapping(value = "/QueryMonth", method = RequestMethod.GET)
    @ResponseBody
    public double QueryMonth(@RequestBody Integer storeid) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        //获取当前月第一天：
        Calendar calstr = Calendar.getInstance();
        //本月
        calstr.add(Calendar.MONTH, 0);
        //设置为1号为本月第一天
        calstr.set(Calendar.DAY_OF_MONTH, 1);
        String monthtime = df.format(calstr.getTime());
        String endtime = df.format(new Date());// new Date()为获取当前系统时间
        double msq = ordersService2.QueryMonth(monthtime, endtime, storeid);
        return msq;
    }

    /**
     * 获取某个分店当天的账单总额
     *
     * @return
     */
    @RequestMapping("/QueryDay")
    @ResponseBody
    public double QueryDay(@RequestBody Integer storeid) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        String daytime = df.format(new Date());// new Date()为获取当前系统时间
        double Day = ordersService2.QueryDay(daytime, storeid);
        return Day;
    }

    /**
     * 获取某个分店本周账单总额
     *
     * @param storeid 分店ID
     * @return
     */
    @RequestMapping("/QueryWeek")
    @ResponseBody
    public double QueryWeek(@RequestBody Integer storeid) {
        String monthtime, endtime, curWeek;
        Calendar curStartCal = Calendar.getInstance();
        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
        SimpleDateFormat dfWeek = new SimpleDateFormat("(第ww周)");
        Calendar cal = (Calendar) curStartCal.clone();
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        monthtime = df.format(cal.getTime());
        curWeek = dfWeek.format(cal.getTime());
        cal.add(Calendar.DATE, 6);
        endtime = df.format(cal.getTime());
        double week = ordersService2.QueryMonth(monthtime, endtime, storeid);
        return week;
    }

    /**
     * 获取某个分店的年账单总额
     *
     * @param storeid 分店ID
     * @return
     */
    @RequestMapping("/QueryYear")
    @ResponseBody
    public double QueryYear(@RequestBody Integer storeid) {
        String monthtime = formatDate(getCurrYearFirst());
        String endtime = formatDate(getCurrYearLast());
        double year = ordersService2.QueryMonth(monthtime, endtime, storeid);
        return year;
    }


    //底下的是订单数

    /**
     * 获取某个分店当日账单总数
     *
     * @param storeid
     * @return
     */
    @RequestMapping("/QueryDayOrder")
    @ResponseBody
    public int QueryDayOrder(Integer storeid) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        String endtime = df.format(new Date());// new Date()为获取当前系统时间
        int dayorder = ordersService2.QueryRorder(endtime, storeid);
        return dayorder;
    }

    /**
     * 获取某个分店本周账单总数
     *
     * @param storeid
     * @return
     */
    @RequestMapping("/QueryWeekOrder")
    @ResponseBody
    public int QueryWeekOrder(Integer storeid) {
        String monthtime, endtime, curWeek;
        Calendar curStartCal = Calendar.getInstance();
        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
        SimpleDateFormat dfWeek = new SimpleDateFormat("(第ww周)");
        Calendar cal = (Calendar) curStartCal.clone();
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        monthtime = df.format(cal.getTime());
        curWeek = dfWeek.format(cal.getTime());
        cal.add(Calendar.DATE, 6);
        endtime = df.format(cal.getTime());
        int weekorder = ordersService2.QueryDayOrder(monthtime, endtime, storeid);
        return weekorder;
    }

    /**
     * 某个分店的月账单总数
     *
     * @param storeid
     * @return
     */
    @RequestMapping("/QueryMonthOrder")
    @ResponseBody
    public int QueryMonthOrder(Integer storeid) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        //获取当前月第一天：
        Calendar calstr = Calendar.getInstance();
        //本月
        calstr.add(Calendar.MONTH, 0);
        //设置为1号为本月第一天
        calstr.set(Calendar.DAY_OF_MONTH, 1);
        String monthtime = df.format(calstr.getTime());
        String endtime = df.format(new Date());// new Date()为获取当前系统时间
        int monthorder = ordersService2.QueryDayOrder(monthtime, endtime, storeid);
        return monthorder;
    }

    /**
     * 某个分店的年账单总数
     *
     * @param storeid
     * @return
     */
    @RequestMapping("/QueryYearOrder")
    @ResponseBody
    public int QueryYearOrder(Integer storeid) {
        String monthtime = formatDate(getCurrYearFirst());
        String endtime = formatDate(getCurrYearLast());
        int yearorder = ordersService2.QueryDayOrder(monthtime, endtime, storeid);
        return yearorder;
    }

    /**
     * 查询账单
     */
    @RequestMapping("/QueryOrders")
    @ResponseBody
    public List<Orders> QueryOrders() {
        List list = ordersService2.selectAllOrders();
        return list;
    }

    /**
     * 根据条件查询账单
     */
    @ResponseBody
    @RequestMapping("/selectAllDate")
    public List<Orders> selectAllDate(@RequestParam(name = "createordertime", required = false) String createordertime, @RequestParam(name = "id", required = false) Integer id) {
        List listDate = null;
        if (createordertime != null || id != null) {
            listDate = ordersService2.selectAllDate(createordertime, id);
        } else {
            System.out.println(listDate + "这里的值为空");
        }
        return listDate;
    }
    private static ThreadLocal<Orders> ors = new ThreadLocal<>();
    private Orders oldorder = null;

    //支付成功后修改订单状态
    @RequestMapping("/updOrderzfb")
    public int updOrderzfb() {
        int count = 0;
        if (oldorder.getId() != null) {
            Orders o = new Orders();
            o.setId(oldorder.getId());
            o.setEndtime(new Date());
            o.setState(1);
            count = ordersService2.updateOrder(o);
        }
        return count;
    }

    //购物车提交订单返回订单id
    @RequestMapping("/createOrder")
    public int createOrder(@RequestBody Orders orders) {
        orders.setCreateordertime(new Date());
        int count = ordersService2.insert(orders);
        int id = 0;
        if (count == 1) {
            id = ordersService2.getOrderLastId();
        }
        return id;
    }

    /**
     * @Title: AlipayController.java
     * @Package com.sihai.controller
     * @Description: 前往支付宝第三方网关进行支付
     * Copyright: Copyright (c) 2017
     * Company:FURUIBOKE.SCIENCE.AND.TECHNOLOGY
     * @author sihai
     * @date 2017年8月23日 下午8:50:43
     * @version V1.0
     * http://xh3zrv.natappfree.cc/goAlipay
     */
    @RequestMapping(value = "/goAlipay", produces = "text/html; charset=UTF-8")
    public String goAlipay(Integer id, String phone, Long pricetotal, HttpServletRequest request, HttpServletRequest response) throws Exception {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setPhone(phone);
        orders.setPricetotal(pricetotal);
        ors.set(orders);
        oldorder = ors.get();

        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = orders.getId().toString();
        //付款金额，必填
        String total_amount = orders.getPricetotal().toString();
        //订单名称，必填
        String subject = orders.getPhone();
        //商品描述，可空
        String body = "用户订购商品个数：" + "";

        // 该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。 该参数数值不接受小数点， 如 1.5h，可转换为 90m。
        String timeout_express = "1c";

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"timeout_express\":\"" + timeout_express + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        return result;
    }


    @RequestMapping("/QueryAllOrder")
    @ResponseBody
    public HashMap<String, ShoppingTest> QueryAllOrders(Integer userid)
    {
        HashMap<String, ShoppingTest> list=feignShoppingService.QueryAllOrder(userid);
        return list;
    }

    @RequestMapping("/QueryOrdertoState")
    @ResponseBody
    public HashMap<String, ShoppingTest> QueryOrdertoState(Integer userid,Integer state)
    {
        HashMap<String, ShoppingTest> list=feignShoppingService.QueryOrdertoState(userid,state);
        return list;
    }
}
